package com.sjx.lib_weather

import android.annotation.SuppressLint
import android.util.Log
import android.view.MenuItem
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.sjx.lib_base.BaseActivity
import com.sjx.lib_base.com.sjx.lib_base.callback.BaiduLocationListener
import com.sjx.lib_base.com.sjx.lib_base.callback.LocationCallback
import com.sjx.lib_base.manager.ARouterManager
import com.sjx.lib_base.manager.PermissionsManager
import com.sjx.lib_network.HttpManager
import com.sjx.lib_network.bean.DailyWeatherResponse
import com.sjx.lib_network.bean.HourlyWeatherResponse
import com.sjx.lib_network.bean.WeatherResponse
import com.sjx.lib_weather.adapter.DailyAdapter
import com.sjx.lib_weather.adapter.HourlyAdapter
import com.sjx.lib_weather.databinding.ActivityWeatherBinding
import com.yanzhenjie.permission.Action
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


/**
 * FileName: WeatherActivity
 * Founder: sjx
 * Profile: 天气活动
 */
@Route(path = ARouterManager.PATH_WEATHER)
class WeatherActivity : BaseActivity<ActivityWeatherBinding>(), LocationCallback {

    private val TAG = WeatherActivity::class.simpleName

    private var district: String? = null

    private var mLocationClient: LocationClient? = null
    private val myListener: BaiduLocationListener = BaiduLocationListener()

    override fun getLayoutId() = R.layout.activity_weather

    override fun isShowBack() = true

    override fun getTitleText() = "天气"

    override fun initView() {
        with(binding) {
            includeVis.textView2.text = "能见度"
            includeHumidity.textView2.text = "湿度"
            includeWind.textView2.text = "风速"
            includePrecipitation.textView2.text = "降水量"
            includeCloud.textView2.text = "云量"
            includePressure.textView2.text = "气压"
        }
        window.statusBarColor = ContextCompat.getColor(this, R.color.colorBlue)
        setSupportActionBar(findViewById(R.id.weather_toolbar))
        supportActionBar?.let {
            it.setDisplayHomeAsUpEnabled(true)
            it.setHomeAsUpIndicator(R.drawable.icon_menu)
        }
        initLocation()
        if (PermissionsManager.checkPermission(
                this,
                PermissionsManager.permissionLocationAndStorage
            )
        ) {
            startLocation()
        } else {
            PermissionsManager.requestPermission(
                this, PermissionsManager.permissionLocationAndStorage, Action<List<String>> {
                    startLocation()
                }
            )
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> binding.weatherDrawerLayout.openDrawer(GravityCompat.START)
        }
        return true
    }

    private fun initLocation() {
        try {
            mLocationClient = LocationClient(application)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (mLocationClient != null) {
            myListener.setCallback(this)
            val option = LocationClientOption()
            //如果开发者需要获得当前点的地址信息，此处必须为true
            option.setIsNeedAddress(true)
            //可选，设置是否需要最新版本的地址信息。默认不需要，即参数为false
            option.setNeedNewVersionRgc(true)
            //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
            mLocationClient!!.locOption = option
            //注册定位监听
            mLocationClient!!.registerLocationListener(myListener)
        }
    }


    private fun startLocation() {
        if (mLocationClient != null) {
            mLocationClient!!.start()
        }
    }

    override fun onReceiveLocation(bdLocation: BDLocation?) {
        val latitude = bdLocation?.latitude   //获取纬度信息
        val longitude = bdLocation?.longitude    //获取经度信息
        val radius = bdLocation?.radius    //获取定位精度，默认值为0.0f
        val coorType = bdLocation?.coorType
        //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
        val errorCode = bdLocation?.locType//161  表示网络定位结果
        //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
        val addr = bdLocation?.addrStr    //获取详细地址信息
        val country = bdLocation?.country    //获取国家
        val province = bdLocation?.province    //获取省份
        val city = bdLocation?.city   //获取城市
        district = bdLocation?.district    //获取区县
        val street = bdLocation?.street    //获取街道信息
        val locationDescribe = bdLocation?.locationDescribe    //获取位置描述信息
        queryLocationWeather(longitude.toString(), latitude.toString())
        queryLocationHourlyWeather(longitude.toString(), latitude.toString())
        queryLocationDailyWeather(longitude.toString(), latitude.toString())
    }

    private fun queryLocationWeather(longitude: String, latitude: String) {
        HttpManager.queryNow("$longitude,$latitude", object : Callback<WeatherResponse> {
            @SuppressLint("SetTextI18n")
            override fun onResponse(
                call: Call<WeatherResponse>,
                response: Response<WeatherResponse>
            ) {
                if (response.isSuccessful) {
                    loadData(response.body())
                }
            }

            override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {
                Log.i(TAG, "onFailure:$t")
            }

        })
    }

    private fun queryLocationHourlyWeather(longitude: String, latitude: String) {
        HttpManager.queryHourly("$longitude,$latitude", object : Callback<HourlyWeatherResponse> {
            @SuppressLint("SetTextI18n")
            override fun onResponse(
                call: Call<HourlyWeatherResponse>,
                response: Response<HourlyWeatherResponse>
            ) {
                if (response.isSuccessful) {
                    Log.i(TAG, "onResponse: ${response.code()}")
                    Log.i(TAG, "onResponse: ${response.body()}")
                    loadHourlyData(response.body())
                }
            }

            override fun onFailure(call: Call<HourlyWeatherResponse>, t: Throwable) {
                Log.i(TAG, "onFailure:$t")
            }

        })
    }

    private fun queryLocationDailyWeather(longitude: String, latitude: String) {
        HttpManager.queryDaily("$longitude,$latitude", object : Callback<DailyWeatherResponse> {
            @SuppressLint("SetTextI18n")
            override fun onResponse(
                call: Call<DailyWeatherResponse>,
                response: Response<DailyWeatherResponse>
            ) {
                if (response.isSuccessful) {
                    Log.i(TAG, "onResponse: ${response.code()}")
                    Log.i(TAG, "onResponse: ${response.body()}")
                    loadDailyData(response.body())
                }
            }

            override fun onFailure(call: Call<DailyWeatherResponse>, t: Throwable) {
                Log.i(TAG, "onFailure:$t")
            }

        })
    }

    private fun loadData(response: WeatherResponse?) {
        if (response != null) {
            with(binding) {
                tvTemp.text = response.now?.temp
                tvWeatherPhenomenon.text = response.now?.text
                tvLocation.text = district
                tvTotalTemp.text = response.now?.feelsLike
                includeVis.textView3.text = response.now?.vis
                includeHumidity.textView3.text = response.now?.humidity
                includeWind.textView3.text = response.now?.windSpeed
                includePrecipitation.textView3.text = response.now?.precip
                includeCloud.textView3.text = response.now?.cloud
                includePressure.textView3.text = response.now?.pressure
            }
        }
    }

    private fun loadHourlyData(response: HourlyWeatherResponse?) {
        val hourlyAdapter = response?.hourly?.let { HourlyAdapter(it) }
        val managerHourly = LinearLayoutManager(this)
        managerHourly.orientation = RecyclerView.HORIZONTAL
        with(binding.rvHourly) {
            layoutManager = managerHourly
            adapter = hourlyAdapter
        }
    }

    private fun loadDailyData(response: DailyWeatherResponse?) {
        val dailyAdapter = response?.daily?.let { DailyAdapter(it) }
        val managerHourly = LinearLayoutManager(this)
        managerHourly.orientation = RecyclerView.VERTICAL
        with(binding.rvDaily) {
            layoutManager = managerHourly
            adapter = dailyAdapter
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.unRegisterLocationListener(myListener)
    }


}